package com.wnhz.work.yz.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.AllLookDetialsAdapter;
import com.wnhz.work.yz.adapter.LookDetialsAdapter;
import com.wnhz.work.yz.bean.AllocationBean;
import com.wnhz.work.yz.bean.LookDetailsBean;
import com.wnhz.work.yz.bean.LookDetialNumsBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class YuShouADUActivity extends BaseActivity implements View.OnClickListener {
    private static final int REPLACE = 1001;//替换
    private static final int ADDEDWASH = 1002;//新增
    private ListView my_listView;
    private TextView tv_all_price;
    private TextView tv_reset;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yu_shou_adu);
        initData();
        initTitle();
        initView();
        EventBus.getDefault().register(this);
    }

    // 在Android的主线程中运行
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatePrice(LookDetialNumsBean b) {
        tv_all_price.setText(getPrice());
    }

    private void initView() {
        tv_reset = (TextView) findViewById(R.id.tv_reset);
        tv_reset.setOnClickListener(this);
        tv_all_price = (TextView) findViewById(R.id.tv_all_price);

        my_listView = (ListView) findViewById(R.id.my_listView);
        upload();
    }

    private LookDetialsAdapter adapter;
    private LookDetailsBean bean = new LookDetailsBean();

    private void upload() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("goods_id", goods_id);
        map.put("sku_id", sku_id);
        XUtil.Post(Url.BOOKING_BOOKINGPACKAGEPRICING, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("qwew", result + "");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        bean = gson.fromJson(result, LookDetailsBean.class);
                    } else {
                        String info = jsonObject.optString("info");
                        MyToast(info);
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                findViewById(R.id.submit).setVisibility(View.VISIBLE);
                setData();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }


    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("单套配置");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setText("下一步");
        submit.setOnClickListener(this);

    }

    private String sku_id, goods_id, budget_id,nums;

    private void initData() {
        sku_id = getIntent().getStringExtra("sku_id");
        goods_id = getIntent().getStringExtra("goods_id");
        budget_id = getIntent().getStringExtra("budget_id");
        nums=getIntent().getStringExtra("nums");
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.submit:
                int hava = 0;
                for (int i = 0; i < bean.getInfo().getCate_info().size(); i++) {
                    for (int j = 0; j < bean.getInfo().getCate_info().get(i).getData().size(); j++) {
                        if (Integer.parseInt(bean.getInfo().getCate_info().get(i).getData().get(j).getGoods_nums()) > 0) {
                            hava++;
                        }
                    }
                }
                if (hava == 0) {
                    MyToast("请至少选择一个商品");
                    return;
                }


                intent = new Intent(this, AddIndustryActivity.class);
                intent.putExtra("isYushou", 12);
                intent.putExtra("bean", bean);
                intent.putExtra("sku_id", sku_id);
                intent.putExtra("goods_id", goods_id);
                intent.putExtra("total_price", getPrice());
                intent.putExtra("budget_id", budget_id);
                intent.putExtra("nums",nums);
                startActivity(intent);
                break;
            //新增主体
            case R.id.tv_add:
                int position = (int) v.getTag();
                intent = new Intent(this, AddedWashActivity.class);
                intent.putExtra("position", position);
                intent.putExtra("packageId", goods_id);
                intent.putExtra("cateId", bean.getInfo().getCate_info().get(position).getCate_id());
                startActivityForResult(intent, ADDEDWASH);
                break;
            case R.id.tv_reset:
                showDialogv7("是否重置？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        upload();
                    }
                });
                break;

        }
    }

    private void setData() {
        tv_all_price.setText(bean.getInfo().getTotal_price() + "");
        adapter = new LookDetialsAdapter(this, bean.getInfo().getCate_info(), this, my_listView);
        adapter.setMyMenuItemClickListener(new LookDetialsAdapter.MyMenuItemClickListener() {
            @Override
            public void onMenuClick(SwipeMenuListView sm_list, AllLookDetialsAdapter mAdapter, int max_position, int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        Intent intent = new Intent(YuShouADUActivity.this, ReplaceActivity.class);
                        intent.putExtra("goodsId", bean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_id());
                        intent.putExtra("max_position", max_position);
                        intent.putExtra("position", position);
                        intent.putExtra("packageId", goods_id);
                        // intent.putExtra("packageId", bean.getInfo().getCate_info().get(max_position).ge);
                        intent.putExtra("nums", bean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_nums());
                        startActivityForResult(intent, REPLACE);
                        mAdapter.notifyDataSetChanged();
                        sm_list.smoothOpenMenu(position);
                        adapter.notifyDataSetChanged();
                        break;

                    case 1:
//                        showDialogv7("确认删除吗?", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                            }
//                        });
                        double allPrice = Double.parseDouble(tv_all_price.getText().toString());
                        double price1 = Double.parseDouble(bean.getInfo().getPrice());
                        double oPrice = Double.parseDouble(bean.getInfo().getOprice());
                        Log.e("m" + max_position, "p" + position);
                        Log.e("----" + bean.getInfo().getCate_info().get(max_position).getData().size() + "", "bb");

                        double deletePrice = Double.parseDouble(bean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_price()) * Double.parseDouble(bean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_nums());
                        String isadd = bean.getInfo().getCate_info().get(max_position).getData().get(position).getIs_old();
                        if ("1".equals(isadd)) {
//                            double li = price1 / oPrice;
                            double li = 1;
                            double bili = getdoublePrice(li);
                            double getPrice = allPrice - bili * deletePrice;
                            double f1 = getdoublePrice(getPrice);
                            // MyToast(f1 + "");
                            if (f1 > 0) {
                                tv_all_price.setText(f1 + "");
                            } else {
                                tv_all_price.setText("0.00");
                            }
                        } else {
                            double price = allPrice - deletePrice;
                            double f2 = getdoublePrice(price);
                            if (f2 > 0) {
                                tv_all_price.setText(f2 + "");
                            } else {
                                tv_all_price.setText("0.00");
                            }
                        }
                        bean.getInfo().getCate_info().get(max_position).getData().remove(position);
                        mAdapter.notifyDataSetChanged();
                        adapter.notifyDataSetChanged();
                        break;

                    default:
                        break;
                }
            }
        });
        my_listView.setAdapter(adapter);
    }

    private double getdoublePrice(double price) {
        BigDecimal d = new BigDecimal(price);
        return d.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    private String getPrice() {
        double total = 0;
        for (int i = 0; i < bean.getInfo().getCate_info().size(); i++) {
            for (int j = 0; j < bean.getInfo().getCate_info().get(i).getData().size(); j++) {
                double nums = 1;
                try {
                    nums = Double.parseDouble(bean.getInfo().getCate_info().get(i).getData().get(j).getGoods_nums());
                } catch (Exception e) {
                    nums = 1;
                }
                double price = 0;
                try {
                    price = Double.parseDouble(bean.getInfo().getCate_info().get(i).getData().get(j).getGoods_price());
                } catch (Exception e) {
                    price = 0;
                }
                total += nums * price;

            }
        }
        DecimalFormat df = new DecimalFormat("######0.00");

        return df.format(total) + "";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REPLACE://替换
                if (resultCode == RESULT_OK) {
                    int max_position = data.getIntExtra("max_position", 0);
                    int position = data.getIntExtra("position", 0);
                    AllocationBean bean = (AllocationBean) data.getSerializableExtra("data");
                    this.bean.getInfo().getCate_info().get(max_position).getData().remove(position);
                    LookDetailsBean.InfoEntity.CateInfoEntity.DataEntity dataEntity = a2d(bean);
                    this.bean.getInfo().getCate_info().get(max_position).getData().add(position, dataEntity);
                    double oldPrice = Double.parseDouble(this.bean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_price());
                    double allPrice = Double.parseDouble(tv_all_price.getText().toString());
                    double price1 = Double.parseDouble(this.bean.getInfo().getPrice());
                    double oPrice = Double.parseDouble(this.bean.getInfo().getOprice());
                    double changePrice = Double.parseDouble(this.bean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_price());
                    String isadd = this.bean.getInfo().getCate_info().get(max_position).getData().get(position).getIs_old();
                    if ("1".equals(isadd)) {
                        if (oldPrice > changePrice) {
                            double li = price1 / oPrice;
                            double bili = getdoublePrice(li);
                            double price11 = oldPrice - changePrice;
                            double getPrice = allPrice - bili * price11;
                            double endPrice = getdoublePrice(getPrice);
                            tv_all_price.setText(endPrice + "");
                        } else {
                            double end = changePrice - oldPrice;
                            double eprice = allPrice + end;
                            double endPrice = getdoublePrice(eprice);
                            tv_all_price.setText(endPrice + "");
                        }
                    } else {
                        if (oldPrice > changePrice) {
                            double price11 = oldPrice - changePrice;
                            double getPrice = allPrice - price11;
                            double endPrice = getdoublePrice(getPrice);
                            tv_all_price.setText(endPrice + "");
                        } else {
                            double end = changePrice - oldPrice;
                            double eprice = allPrice + end;
                            double endPrice = getdoublePrice(eprice);
                            tv_all_price.setText(endPrice + "");
                        }
                    }
                    tv_all_price.setText(getPrice());
                    adapter.notifyDataSetChanged();

                }
                break;

            case ADDEDWASH://新增
                if (resultCode == RESULT_OK) {
                    int position = data.getIntExtra("position", 0);
                    AllocationBean bean = (AllocationBean) data.getSerializableExtra("data");
                    LookDetailsBean.InfoEntity.CateInfoEntity.DataEntity dataEntity = a2d(bean);
                    this.bean.getInfo().getCate_info().get(position).getData().add(dataEntity);
                    double allPrice = Double.parseDouble(tv_all_price.getText().toString());
                    double addPrice = Double.parseDouble(bean.getGoods_price());
                    double price = addPrice + allPrice;
                    double f2 = getdoublePrice(price);
                    tv_all_price.setText(f2 + "");
                    tv_all_price.setText(getPrice());
                    adapter.notifyDataSetChanged();
                }
                break;
            case R.id.tv_reset:
                showDialogv7("是否重置？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        upload();
                    }
                });
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private LookDetailsBean.InfoEntity.CateInfoEntity.DataEntity a2d(AllocationBean bean) {

        LookDetailsBean.InfoEntity.CateInfoEntity.DataEntity dataEntity = new LookDetailsBean.InfoEntity.CateInfoEntity.DataEntity();
        dataEntity.setIs_old(bean.getIs_old());
        dataEntity.setGoods_id(bean.getGoods_id());
        dataEntity.setGoods_name(bean.getGoods_name());
        dataEntity.setGoods_brand(bean.getGoods_brand());
        dataEntity.setGoods_pic(bean.getGoods_pic());
        dataEntity.setGoods_price(bean.getGoods_price());
        dataEntity.setGoods_nums(bean.getGoods_nums());
        dataEntity.setGoods_unit(bean.getGoods_unit());
        dataEntity.setSku_id(bean.getSku_id());
        dataEntity.setSku_info(bean.getSku_info());
        dataEntity.setSelect(false);
        return dataEntity;
    }


}
